import {isPlainObject} from "@/utils/index";

/**
 * 规范内容类型
 * @param headers
 * @param normalizeName
 */
function normalizeHeaderName(headers: any, normalizeName: string): void {
    if (!headers) {
        return;
    }
    Object.keys(headers).forEach(name => {
        if (name !== normalizeName && name.toUpperCase() === normalizeName.toUpperCase()) {
            headers[normalizeName] = headers[name];
        }
    })
}

/**
 * data为普通对象才进行处理
 * @param headers
 * @param data
 */
export function processHeaders(headers: any, data: any): any {
    normalizeHeaderName(headers, 'Content-Type')
    if (isPlainObject(data)) {
        if (headers && !headers['Content-type']) {
            headers['Content-Type'] = 'application/json;charset=utf-8'
        }
    }
    return headers;
}

export function parseHeaders(headers: string): any {
    let parsed = Object.create(null);
    if (!headers) {
        return parsed;
    }
    headers.split('\r\n').forEach(line => {
        let [key, val] = line.split(':');
        key = key.trim().toLowerCase()
        if (!key) {
            return
        }
        if (val) {
            val = val.trim()
        }
        parsed[key] = val;
    })
    return parsed;
}